<template>
  <div class="cb-main-container">
    <div class="search-box">
      <el-form ref="searchForm" :model="search" inline>
        <el-form-item prop="name" label="名称">
          <el-input v-model="search.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="search.status" placeholder="请选择状态" style="width: 150px;">
            <el-option label="全部" value="-1" />
            <el-option v-for="(item, index) in statusEnums" :label="item.label" :value="item.value" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button type="primary" icon="search" @click="onSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-content">
      <div class="operation-box">
        <el-button icon="plus" type="primary" @click="onAdd">新增</el-button>
      </div>
      <div class="table-box">
        <el-table :data="data" size="large" empty-text="暂无数据">
          <el-table-column type="index" width="50" />
          <el-table-column property="name" label="名称" />
          <el-table-column property="address" label="地址" show-overflow-tooltip />
          <el-table-column property="contactPerson" label="联系人" />
          <el-table-column property="contactPhone" label="联系方式" />
          <el-table-column property="assignedEmployeeName" label="负责人" />
          <el-table-column property="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'primary' : 'info'">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column property="createTime" label="创建时间" />
          <el-table-column label="操作" align="right">
            <template #default="scope">
              <el-button icon="edit" link type="primary" @click="onEdit(scope.row)">编辑</el-button>
              <el-button icon="delete" link type="danger" @click="onDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
        <el-pagination background layout="prev, pager, next" :total="search.total" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增/编辑-START -->
    <el-drawer v-model="drawer.visible" size="35%" :title="drawer.title" :close-on-click-modal="false" @close="onDrawerCloseHandle">
      <div class="cb-drawer-container">
        <div class="cb-main">
          <el-form ref="form" :model="model" :label-width="formConfig.labelWidth" :rules="formConfig.rules">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="code" label="编码">
                  <el-input v-model="model.code" disabled placeholder="由系统自动生成" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="name" label="名称">
                  <el-input v-model="model.name" placeholder="供应商名称" maxlength="32" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="area" label="城市">
                  <el-cascader style="width: 100%"
                               placeholder="请选择所在区域"
                               v-model="model.area"
                               :options="cascaderConfig.options"
                               :props="cascaderConfig.props"
                               @change="areaCascaderChangeHandle"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="address" label="详细地址">
                  <el-input v-model="model.address" maxlength="128" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="settlementDeadline" label="结算周期">
                  <el-select v-model="model.settlementDeadline" placeholder="请选择结算周期">
                    <el-option v-for="(item, index) in settlementDeadlineEnums" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="level" label="级别">
                  <el-select v-model="model.level" placeholder="请选择级别">
                    <el-option v-for="(item, index) in levelEnums" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="contactPerson" label="联系人">
                  <el-input v-model="model.contactPerson" placeholder="请填写联系人" maxlength="16" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="contactPhone" label="联系方式">
                  <el-input v-model="model.contactPhone" placeholder="请填写联系方式" maxlength="12" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="assignedEmployeeId" label="负责人">
                  <el-input-tag v-model="inputTagData" readonly @click="onInputTagClick"></el-input-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="status" label="状态">
                  <el-select v-model="model.status" placeholder="请选择状态">
                    <el-option v-for="(item, index) in statusEnums" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item prop="remark" label="备注">
              <el-input type="textarea" v-model="model.remark" placeholder="请输入备注信息" :rows="8" show-word-limit maxlength="500" />
            </el-form-item>

            <el-tabs v-model="drawer.tabActiveName" class="demo-tabs">
              <el-tab-pane label="发票" name="invoice" style="padding-top: 8px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item prop="title" label="抬头">
                      <el-input v-model="model.invoice.title" placeholder="请输入抬头" maxlength="32" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="title" label="税号">
                      <el-input v-model="model.invoice.taxId" placeholder="请输入税号" maxlength="64" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item prop="title" label="税种">
                      <el-select v-model="model.invoice.taxType" placeholder="请选择税种">
                        <el-option v-for="(item, index) in taxTypeEnums" :key="index" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="title" label="税率">
                      <el-input v-model="model.invoice.taxRate" placeholder="请输入税率" maxlength="32" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item prop="title" label="开户银行">
                      <el-input v-model="model.invoice.bankName" placeholder="请输入开户银行" maxlength="32" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item prop="title" label="开户账号">
                      <el-input v-model="model.invoice.bankAccount" placeholder="请输入开户账号" maxlength="64" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </div>
        <div class="cb-footer">
          <el-button type="info" @click="onDrawerCancel">取消</el-button>
          <el-button type="primary" @click="onDrawerConfirm">确认</el-button>
        </div>
      </div>
    </el-drawer>
    <!-- 新增/编辑-END -->

    <!-- 用户选择器S -->
    <sys-user-selector v-model:visible="drawer.sysUserSelectorVisible" @select="onInputTagSelect" :selected-ids="[model.assignedEmployeeId]" />
    <!-- 用户选择器E -->
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from "vue";
import { pageList, add, update, deleteById, detail } from '@/api/erp/supplier.js'
import {ElMessageBox} from "element-plus";
import { clear } from '@/util/ObjectUtil.js'
import { provinceCityTree } from '@/api/common/area.js'
import SysUserSelector from "@/components/system/sys-user-selector.vue";

defineOptions({
  name: '/erp/baseData/supplierManage/supplier'
})

const formConfig = reactive({
  labelWidth: 78,
  rules: {
    name: [
      {required: true, message: '名称不能为空', trigger: 'blur'}
    ],
    address: [
      {required: true, message: '详细地址不能为空', trigger: 'blur'}
    ],
    contactPerson: [
      {required: true, message: '联系人不能为空', trigger: 'blur'}
    ],
    contactPhone: [
      {required: true, message: '联系方式不能为空', trigger: 'blur'}
    ]
  }
})

const cascaderConfig = reactive({
  options: [],
  props: {
    value: 'id',
    label: 'name'
  }
})

const statusEnums = [
  {label: '正常', value: 1},
  {label: '合同到期', value: 2},
  {label: '暂停合作', value: 3},
  {label: '终止合作', value: 4},
]

const levelEnums = [
  {label: '一级', value: 1},
  {label: '二级', value: 2},
  {label: '三级', value: 3},
]

const settlementDeadlineEnums = [
  {label: '现结', value: 1},
  {label: '月结', value: 2},
  {label: '季结', value: 3},
]

const taxTypeEnums = [
  {label: '增值税普通发票', value: 1},
  {label: '增值税专用发票', value: 2}
]

const drawer = reactive({
  visible: false,
  title: '新增',
  tabActiveName: 'invoice',
  sysUserSelectorVisible: false
})

const search = ref({
  name: '',
  status: '',
  pageNo: 1,
  total: 0
})
const searchForm = ref(null)

const model = ref({
  id: '',
  code: '',
  name: '',
  area: [],
  provinceId: '',
  cityId: '',
  address: '',
  status: '',
  settlementDeadline: '',
  level: '',
  assignedEmployeeId: '',
  assignedEmployeeName: '',
  invoice: {
    id: '',
    title: '',
    taxId: '',
    taxType: '',
    taxRate: '',
    bankName: '',
    bankAccount: ''
  },
  contactPerson: '',
  contactPhone: '',
  remark: ''
})
const form = ref(null)
const data = ref([
  {id: '1', code: 'CBS001', name: '测试名称', area: [], provinceId: '', cityId: '', address: '测试地址', status: 1, settlementDeadline: '', level: '', assignedEmployeeId: '3', assignedEmployeeName: '张三', invoice: {}, contactPerson: '李四', contactPhone: '18688888888', createTime: '2025-05-21 12:00:00'}
])

const getStatusText = (status) => {
  let statusText = '未知'
  for (let item of statusEnums) {
    if (item.value === status) {
      statusText = item.label
      break
    }
  }

  return statusText
}

const inputTagData = computed(() => {
  if (model.value.assignedEmployeeName) {
    return [model.value.assignedEmployeeName]
  } else {
    return  []
  }
})

// 重置搜索表单
const onReset = () => {
  searchForm.value.resetFields()
  search.value.pageNo = 1
  requestPageList()
}

// 搜索
const onSearch = () => {
  search.value.pageNo = 1
  requestPageList()
}

// 新增
const onAdd = () => {
  provinceCityTree().then(resp => {
    cascaderConfig.options = resp.data
  })
  drawer.title = '新增'
  drawer.visible = true
}

const onEdit = (rowData) => {
  detail(rowData.id).then(resp => {
    model.value = {...resp.data}
    drawer.title = '编辑'
    drawer.visible = true
  })
}

const onDel = (rowData) => {
  ElMessageBox.confirm('您确定要删除这条数据吗?', '提示', {
    cancelButtonText: '退出',
    confirmButtonText: '确定'
  }).then(() => {
    deleteById(rowData.id).then(() => {
      requestPageList()
    })
  })
}

const onDrawerCancel = () => {
  drawer.visible = false
}

const onDrawerConfirm = async () => {
  const valid = await form.value.validate()
  if (valid) {
    if (model.value.id) {
      await update(model.value)
    } else {
      await add(model.value)
    }
    requestPageList()

    drawer.visible = false
  }
}

const onDrawerCloseHandle = () => {
  form.value.resetFields()
  clear(model.value)
}

const handleCurrentChange = (currentPage) => {
  search.value.pageNo = currentPage
  requestPageList()
}

const requestPageList = () => {
  pageList(search.value).then(resp => {
    data.value = resp.data.data
    search.value.total = Number.parseInt(resp.data.total)
  })
}

const areaCascaderChangeHandle = (data) => {
  model.value.provinceId = data[0]
  model.value.cityId = data[1]
}

const onInputTagClick = () => {
  drawer.sysUserSelectorVisible = true
}

const onInputTagSelect = (select) => {
  if (select.length >= 1) {
    let selectItem = select[0]
    model.value.assignedEmployeeId = selectItem.id
    model.value.assignedEmployeeName = selectItem.name

    drawer.sysUserSelectorVisible = false
  }
}

onMounted(() => {
  requestPageList()
})
</script>

<style scoped lang="scss">
.cb-main-container {
  display: flex;
  flex-direction: column;

  .search-box {
    @include containerStyle;
    padding-bottom: 0;
  }

  .main-content {
    flex: 2;
    @include containerStyle;

    display: flex;
    flex-direction: column;

    .table-box {
      flex: 2;
      margin-bottom: $cb_margin-value;
    }
  }

  .cb-drawer-container {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    .cb-main {
      flex-grow: 2;
    }

    .cb-footer {
      width: 100%;
      height: 26px;
      margin-top: $cb-margin-sm;
      text-align: right;
    }
  }
}
</style>
